﻿
@{
    Layout = "";
}

<div ng-controller="DrawEditCtrl">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <form name="formValidate" ng-submit="submitForm()" novalidate="" class="form-validate form-horizontal">
                    <div class="panel panel-default" ng-class="{ 'whirl standard': isLoading}">
                        <div class="panel-body">
                            <fieldset class="b0">
                                <legend>{{ThisDraw.Id == 0 || ThisDraw.Id == null ? '添加抽奖活动' : '修改抽奖活动'}}</legend>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">活动名称</label>
                                    <div class="col-sm-6">
                                        <div class="form-inline">
                                            <input style="width: 70%;" type="text" name="name" required="" ng-model="ThisDraw.DrawName" class="form-control" maxlength="200" />
                                        </div>
                                        <span ng-show="validateInput('name', 'required')" class="text-danger">请输入活动名称</span>
                                    </div>
                                    <div class="col-sm-2">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">消耗积分</label>
                                    <div class="col-sm-2">
                                        <input type="number" ng-model="ThisDraw.ConsumePoints" class="form-control" name="points" maxlength="8"
                                               ng-pattern="/^\d+$/" />                                      
                                        <span ng-show="validateInput('points', 'pattern')" class="text-danger">请填写正确的积分值</span>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">抽奖次数(默认为0，代表不限次数)</label>
                                    <div class="col-sm-2">
                                        <input type="number" ng-model="ThisDraw.Chances" class="form-control" name="chances" maxlength="8"
                                               ng-pattern="/^\d+$/" />
                                        <span ng-show="validateInput('chances', 'pattern')" class="text-danger">请填写正确的抽奖次数</span>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">排序（数值大的靠前）</label>
                                    <div class="col-sm-2">
                                        <input type="number" ng-model="ThisDraw.Sort" class="form-control" name="sort" maxlength="8"
                                               ng-pattern="/^\d+$/" />
                                        <span ng-show="validateInput('sort', 'pattern')" class="text-danger">请填写正确的排序号</span>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">开始时间</label>
                                    <div class="col-sm-4">
                                        <p class="input-group">
                                            <input ng-model="ThisDraw.StartTime"  readonly="readonly" style="z-index: 0;" name="StartTime" required="" type="text" class="form-control" datetime-picker="yyyy-MM-dd HH:mm:ss"
                                                   is-open="picker1.open" datepicker-options="datepickerOptions" />
                                            <span class="input-group-btn">
                                                <button type="button" class="btn btn-default" ng-click="openCalendar($event, 'picker1')"><i class="fa fa-calendar"></i></button>
                                            </span>
                                        </p>
                                        <span ng-show="validateInput('StartTime', 'required')" class="text-danger">请输入开始时间</span>
                                    </div>
                                    <div class="col-sm-4">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">结束时间</label>
                                    <div class="col-sm-4">
                                        <p class="input-group">
                                            <input ng-model="ThisDraw.EndTime" readonly="readonly" style="z-index: 0;" name="EndTime" required="" type="text" class="form-control" datetime-picker="yyyy-MM-dd HH:mm:ss"
                                                   is-open="picker2.open" datepicker-options="datepickerOptions" />
                                            <span class="input-group-btn">
                                                <button type="button" class="btn btn-default" ng-click="openCalendar($event, 'picker2')"><i class="fa fa-calendar"></i></button>
                                            </span>
                                        </p>
                                        <span ng-show="validateInput('EndTime', 'required')" class="text-danger">请输入结束时间</span>
                                    </div>
                                    <div class="col-sm-4">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">活动描述</label>
                                    <div class="col-sm-4">
                                        <textarea rows="4" ng-model="ThisDraw.Description" class="form-control" maxlength="500"></textarea>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">抽奖说明</label>
                                    <div class="col-sm-4">
                                        <textarea rows="4" ng-model="ThisDraw.AwardDes" class="form-control" maxlength="500"></textarea>
                                    </div>
                                </div>
                            </fieldset>
                            <fieldset>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">封面</label>
                                    <div class="col-sm-2">
                                        <div class="imgcrop-preview">
                                            <img ng-src="{{myCroppedImage}}" style="max-width: 100%; max-height: 100%" onerror="javascript: this.src = '/Content/img/default.png';" />
                                            <input id="fileInput" class="ng-hide" type="file" nv-file-select="" uploader="uploader" />
                                        </div>
                                        <div>
                                            <div style="" class="progress progress-xs" ng-show="uploading">
                                                <div role="progressbar" ng-style="{ 'width': uploader.progress + '%' }" class="progress-bar"></div>
                                            </div>
                                        </div>
                                        <span ng-show="IsCheckedPic" class="text-danger">请选择封面图片</span>
                                    </div>
                                    <div class="col-sm-4">
                                        <button type="button" class="mb-sm btn btn-info" ng-click="selectImage()">
                                            图片选择
                                        </button>
                                        <span class="text-danger">建议上传1：1的海报图</span>
                                    </div>
                                    <div class="col-sm-2">
                                        <h4 class="text-danger">*</h4>
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                        <div class="panel-footer text-right">
                            <button type="button" class="btn btn-warning" ng-click="cancel()">返回列表</button>
                            <button type="submit" class="btn btn-primary">保存</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    App.controller("DrawEditCtrl",[
    '$scope', '$resource', '$state','$rootScope', '$route', 'ngDialog', '$http','$stateParams', 'ngTableParams', 'ngTableDataService','FileUploader', 'Notify',
    function ($scope, $resource, $state,$rootScope, $route, ngDialog, $http, $stateParams, ngTableParams, ngTableDataService, FileUploader, Notify) {
        'use strict';
        $scope.submitted = false;
        $scope.ThisDraw = {};
       // $scope.isLoading = true;
        $scope.IsCheckedPic = false;
        $scope.croppedImageList = [];
        //表单验证
        $scope.validateInput = function (name, type) {
            var input = $scope.formValidate[name];
            return (input.$dirty || $scope.submitted) && input.$error[type];
        };

        //数据初始化
        $http.post("/Draw/GetDrawInfo", { Id: $stateParams.Id }).then(function (response) {
            //基本信息
            $scope.ThisDraw= response.data;
            $scope.myCroppedImage = $rootScope.ImgHostUrl + angular.copy(response.data.DrawCover);
            //奖品信息           
        })
        //返回列表页
        $scope.cancel = function () {
            $state.go("app.draw");
        }

        $scope.submitForm = function () {
            $scope.isLoading = true;
            $scope.submitted = true;
            if ($scope.formValidate.$valid) {
                //这里加入一些ng不方便验证的逻辑
                if ($scope.ThisDraw.StartTime > $scope.ThisDraw.EndTime) {
                    Notify.alert('活动开始时间不能大于结束时间!', { status: 'warning', timeout: 1000 });
                    $scope.isLoading = false;
                    return false;
                }

                $http.post("/Draw/SaveDraw", $scope.ThisDraw).then(function (returnData) {
                    if (returnData.data.isSuccess) {
                        Notify.alert('操作成功!', { status: 'success', timeout: 1000 });
                        $state.go("app.draw");
                    } else {
                        Notify.alert(returnData.data.msg, { status: 'warning', timeout: 1000 });
                    }
                    $scope.isLoading = false;
                });
            }
            else {
                $scope.isLoading = false;
                return false;
            }
        }

        ////获取所有有效商品信息
        //$http.post("/Draw/GetActProducts").then(function (response) {
        //    $scope.ActProducts = response.data.Data;
        //});
        ////获取有效的优惠券信息
        //$http.post("/Draw/GetActCoupons").then(function (response) {
        //    $scope.ActCoupons = response.data.Data;
        //});

        //-------------图片选择相关
        $scope.selectImage = function () {
            $("#fileInput").click();
        }

        //-------------图片选择相关
        var handleFileSelect = function (evt) {
            var file = $scope.uploadSelectFile = evt.currentTarget.files[0];
            if (!evt.currentTarget.files[0] || ! /image\/\w+/.test(evt.currentTarget.files[0].type)) {
                Notify.alert('请选择图像文件', { status: 'warning' });
                return false;
            }
            if (file.size > 1 * 1024 * 1024) {
                Notify.alert('图片大小不能大于1MB', { status: 'warning', timeout: 3000 });
                $scope.uploadSelectFile = null;
                return false;
            }
            var reader = new FileReader();
            reader.onload = function (evt) {
                $scope.$apply(function ($scope) {
                    $scope.myCroppedImage = evt.target.result;
                });
            };
            if (file)
                reader.readAsDataURL(file);
        };

        angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);
        var uploader = $scope.uploader = new FileUploader({
            url: $rootScope.ImgUploadUrl + '?PlatForm=wsd&Path=Draw'
        });
        uploader.filters.push({
            name: 'customFilter',
            fn: function (item /*{File|FileLikeObject}*/, options) {
                return this.queue.length < 10;
            }
        });

        // CALLBACKS

        uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
            //  console.info('onWhenAddingFileFailed', item, filter, options);
        };
        uploader.onAfterAddingFile = function (fileItem) {
            if ($scope.uploadSelectFile && /image\/\w+/.test($scope.uploadSelectFile.type)) {
                $scope.uploading = true;
                fileItem.upload();
            }
            //    console.info('onAfterAddingFile', fileItem);
        };
        uploader.onAfterAddingAll = function (addedFileItems) {
            //   console.info('onAfterAddingAll', addedFileItems);
        };
        uploader.onBeforeUploadItem = function (item) {
            // console.info('onBeforeUploadItem', item);

        };
        uploader.onProgressItem = function (fileItem, progress) {
            // console.info('onProgressItem', fileItem, progress);
        };
        uploader.onProgressAll = function (progress) {
            //  console.info('onProgressAll', progress);
        };
        uploader.onSuccessItem = function (fileItem, response, status, headers) {
            $scope.ThisDraw.DrawCover = response[0];
            $("#fileInput").val("");
            //  console.info('onSuccessItem', fileItem, response, status, headers);
        };
        uploader.onErrorItem = function (fileItem, response, status, headers) {
            //  console.info('onErrorItem', fileItem, response, status, headers);
        };
        uploader.onCancelItem = function (fileItem, response, status, headers) {
            // console.info('onCancelItem', fileItem, response, status, headers);
        };
        uploader.onCompleteItem = function (fileItem, response, status, headers) {
            //  console.info('onCompleteItem', fileItem, response, status, headers);
        };
        uploader.onCompleteAll = function () {
            $scope.uploading = false;
        };


        // 日期插件
        $scope.picker1 = {
            date: new Date()
        };

        $scope.picker2 = {
            date: new Date()
        };

        $scope.datepickerOptions = {
            showWeeks: false,
            startingDay: 1,
            dateDisabled: function (data) {
                //return (data.mode === 'day' && (new Date().toDateString() == data.date.toDateString()));
            }
        }
        $scope.openCalendar = function (e, picker) {
            $scope[picker].open = true;
        };
    }])
</script>

